import { BaseDirectory, logDir } from '@tauri-apps/api/path';

export function nextTick(cb: () => void) {
  Promise.resolve().then(cb);
}

export const separator = '@@##@@';

export const logDirPath = 'ra_logs';

export const logBaseDir = BaseDirectory.Log;

export const logBaseDirPath = logDir;

export function getCommandKey(code: string, commandValue: string) {
  return `${code}${separator}${commandValue}`;
}

const defaultStartCommand: () => CommandItem = () => ({
  label: '启动',
  value: 'start',
  command: 'npm start',
  fixed: true,
  key: 'start',
});

export function parseJsonConfig(file: string, path: string) {
  const packageJson = JSON.parse(file || '{}');
  const [dirName] = path.split(/(\\|\/)/gi).reverse();
  const { name, scripts, description } = packageJson;
  let startCommand = defaultStartCommand();
  if (scripts['start']) {
    startCommand = {
      label: 'start',
      value: 'start',
      command: 'npm start',
      key: 'start',
    };
  }
  delete scripts['start'];
  const commandList = Object.entries(scripts).reduce(
    (p: CommandItem[], [key]) => {
      p.push({
        label: key,
        value: key,
        command: `npm run ${key}`,
        key: key,
      });
      return p;
    },
    [],
  );
  commandList.unshift(startCommand);
  return { name: name || dirName, description, commandList };
}
